<?php

defined('SYSPATH') or die('Access error!');

class Model_Q2a_Question extends Model_Q2a_Post
{

    public $rules = array(
        'name' => array
            (
            'not_empty' => null,
            'max_length' => array(60),
        ),
        'content' => array(
            'not_empty' => null,
            'min_length' => array(20)
        )
    );

    public function get_question_list($where_sql = array(), $order_arr = array())
    {
        //获取问题列表的条数
        $setting = self::$setting;
        $records_per_page = isset($setting['q2a_show_list_num']) && !empty($setting['q2a_show_list_num']) ? $setting['q2a_show_list_num'] : 10;
        //获取的条件
        $where_sql = '';
        if (Arr::validate_arr($where_sql))
        {
            $where_sql = $this->get_table_where('p', $where_sql);
        }

        $order_by = ' ORDER BY p.position,p.id DESC';
        if (!empty($order_arr))
        {
            $order_by = $this->order_by($order_arr, 'p');
        }
        $where_sql .= $order_by;


        $sql = "SELECT p.name,p.id,p.add_time,p.view_count,p.points,p.up_votes,p.down_votes,p.comment_count,p.answer_count,u.username,u.avatar,u.id as user_id,u.username" .
                " FROM " . $this->table . " AS p" .
                " LEFT JOIN " . $this->db->get_table('user') . " AS u ON u.id=p.user_id" . $where_sql;
        $data = $this->get_page_list($sql, $records_per_page);

        $temp = array();
        if (Arr::validate_arr($data['list']))
        {
            foreach ($data['list'] as $value)
            {
                //得到关联的标签
                $value['tags'] = (array) $this->get_question_tag_by_id($value['id']);
                $value['votes'] = $value['down_votes'] + $value['up_votes'];
                $value['avatar_path'] = Model::factory('user')->create_avatar_path($value['user_id'], $value['avatar']);
                $temp[] = $value;
            }
            $data['list'] = $temp;
            unset($temp);
        }
        return $data;
    }

    /**
     *  根据分类的id得到问题列表
     * @param type $id
     * @return type
     */
    public function get_question_by_category_id($id = '', $type = Q2A_ALL)
    {
        $setting = self::$setting;
        $records_per_page = $setting['q2a_show_list_num'];
        $where = " WHERE p.post_type='" . Q2A_POST_TYPE_QUESTION . "'";
        $where .= $this->get_question_type_where($type);
        $where .=!empty($id) ? ' AND ' . 'p.category_id=' . $id : '';
        if ($type == Q2A_HOT_QUESTION)
        {
            $where .= ' ORDER BY p.position,p.view_count DESC,p.answer_count DESC,p.id DESC';
        }
        else
        {
            $where .= ' ORDER BY p.position,p.id DESC';
        }
        $sql = "SELECT p.name,p.id,p.content,p.add_time,p.view_count,p.points,p.up_votes,p.down_votes,p.comment_count,p.answer_count,u.username,u.avatar,u.id as user_id,u.username" .
                " FROM " . $this->table . " AS p" .
                " LEFT JOIN " . $this->db->get_table('user') . " AS u ON u.id=p.user_id" . $where;
        $data = $this->get_page_list($sql, $records_per_page);

        $temp = array();
        if (count($data['list']) > 0)
        {
            foreach ($data['list'] as $value)
            {
                //得到关联的标签
                $value['tags'] = (array) $this->get_question_tag_by_id($value['id']);
                $value['votes'] = $value['down_votes'] + $value['up_votes'];

                $value['avatar_path'] = Model::factory('user')->create_avatar_path($value['user_id'], $value['avatar']);

                $temp[] = $value;
            }
            $data['list'] = $temp;
            unset($temp);
        }
        return count($data) > 0 ? $data : array();
    }

    public function get_question_by_tag_id($id = '')
    {
        $setting = self::$setting;
        $records_per_page = $setting['q2a_show_list_num'];
        $where = " WHERE p.post_type='" . Q2A_POST_TYPE_QUESTION . "' AND pt.tag_id=" . $id;
        $sql = "SELECT p.name,p.id,p.content,p.add_time,p.view_count,p.up_votes,p.down_votes,p.comment_count,p.answer_count,u.username,u.id as user_id,u.avatar" .
                " FROM " . $this->table . " AS p" .
                " LEFT JOIN " . $this->db->get_table('q2a_post_tag') . " AS pt ON p.id = pt.post_id" .
                " LEFT JOIN " . $this->db->get_table('user') . " AS u ON u.id=p.user_id" . $where;
        $data = $this->get_page_list($sql, $records_per_page);
        $temp = array();
        if (count($data['list']) > 0)
        {
            foreach ($data['list'] as $value)
            {
                //得到关联的标签
                $value['tags'] = (array) $this->get_question_tag_by_id($value['id']);
                $value['votes'] = $value['down_votes'] + $value['up_votes'];
                $value['avatar_path'] = Model::factory('user')->create_avatar_path($value['user_id'], $value['avatar']);
                $temp[] = $value;
            }
            $data['list'] = $temp;
            unset($temp);
        }
        return count($data) > 0 ? $data : array();
    }

    /**
     *  得到问题的状态条件
     * @param type $type
     * @return string
     */
    public function get_question_type_where($type = Q2A_ALL)
    {
        $where = ' AND ';
        switch ($type)
        {
            case Q2A_ANSWERED:
                $where .= ' answer_count <> 0';
                break;
            case Q2A_UNANSWERED:
                $where .= ' answer_count = 0';
                break;
            default:
                $where .= ' 1=1 ';
        }

        return $where;
    }

    /**
     *  根据所给的分类id获取问答的id
     * @param type $id
     * @return type
     */
    public function get_category_by_parent_id($id)
    {
        $q2a_category = Model_Category::factory('category')->get_category_list('parent_id=' . $id);
        return count($q2a_category) > 0 ? $q2a_category : array();
    }

    /**
     *  插入问题
     * @param array $data
     * @return type
     */
    public function insert_question($data)
    {
        $data['user_id'] = Session::instance()->get_detail('user', 'id');
        $data['notify_email'] = Session::instance()->get_detail('user', 'email');
        $data['latest_activity'] = Date::get_time();
        $data['add_time'] = Date::get_time();
        $data['update_time'] = Date::get_time();
        $data['post_type'] = Q2A_POST_TYPE_QUESTION;
        return $this->insert_post($data);
    }

    /**
     *  插入标签
     * @param type $tags_name
     * @return type
     */
    public function insert_tag($tags_name, $category_id)
    {
        if (empty($tags_name))
            return;

        $tag_array = explode(' ', $tags_name);
        $tag_id_arr = array();
        if (Arr::validate_arr($tag_array))
        {
            foreach ($tag_array as $name)
            {
                $name = trim($name);
                if (empty($name))
                    continue;
                $has_tag = $this->get_tag_by_name($name);

                if (count($has_tag) > 0)
                {
                    $tag_id_arr[] = $has_tag['id'];
                    continue;
                }
                $tag = Model::factory('q2a_tag');
                $data = array();
                $data['name'] = trim($name);
                $data['add_time'] = Date::get_time();
                $data['update_time'] = Date::get_time();
                $data['user_id'] = Session::instance()->get_detail('user', 'id');
                $data['category_id'] = $category_id;
                $tag_id_arr[] = $tag->insert($data);
            }
            return $tag_id_arr;
        }
        return array();
    }

    /**
     *  根据tag的name获取详细信息
     * @param type $tag
     * @return type
     */
    private function get_tag_by_name($name)
    {
        $tag = Model::factory('q2a_tag');
        $tag_detail = $tag->get_tag_by_name($name);

        //问题数量加1
        if (count($tag_detail) > 0)
        {
            $tag->update_tag_post_count($name, $tag_detail['post_count']);
        }
        return $tag_detail;
    }

    /**
     *  插入关联问题与标签数据
     * @param type $question_id
     * @param type $tags_id_array
     */
    public function insert_post_tag($question_id, $tags_id_array)
    {
        Model::factory('q2a_post_tag')->save_post_tag($question_id, $tags_id_array);
    }

    /**
     *  根据问题的id获取问题的标签
     * @param type $id
     * @return type
     */
    public function get_question_tag_by_id($id)
    {
        $post_tag = Model_Q2a_Post_Tag::factory('q2a_post_tag');
        return $post_tag->get_question_tag_by_id($id);
    }

    /**
     *  得到热门标签
     * @param type $id
     * @return type
     */
    public function get_hot_question_tags($id = '')
    {
        $tag = Model_Q2a_Tag::factory('q2a_tag');
        return $tag->get_hot_question_tags($id, self::$setting);
    }

    /**
     *  得到问题的所属用户
     * @param type $id
     * @return type
     */
    public function get_question_user($id)
    {
        return $this->get_post_user($id);
    }

    /**
     *  得到具体的问题 根据ID
     * @param type $id
     * @return type
     */
    public function get_question_by_id($id)
    {
        $question_detail = $this->get_post_by_id($id);
        if (!empty($question_detail))
        {
            $question_detail['tags'] = $this->get_question_tag_by_id($id);
        }
        return $question_detail;
    }

    /**
     *  某个用户的相关问题
     * @param type $user_id
     * @return type
     */
    public function get_user_related_question($user_id)
    {
        $user_related_question = $this->get_user_related_post($user_id, Q2A_POST_TYPE_QUESTION);
        return $this->handle_question($user_related_question, self::$setting['q2a_user_related_leng']);
    }

    /**
     *  某个分类的相关问题
     * @param type $category_id
     * @return type
     */
    public function get_category_related_questions($category_id)
    {
        $category_related_question = $this->get_category_related_post($category_id, Q2A_POST_TYPE_QUESTION);
        return $this->handle_question($category_related_question, self::$setting['q2a_similar_leng']);
    }

    /**
     *  整理输出
     * @param type $question_list_temp
     * @param type $leng
     * @return type
     */
    public function handle_question($question_list_temp, $leng)
    {
        $question_list = array();
        if (count($question_list_temp) > 0)
        {
            foreach ($question_list_temp as $value)
            {
                $value['name'] = Text::limit_chars($value['name'], $leng);
                $value['url'] = URL::site('question/' . $value['id']);
                $question_list[] = $value;
            }
            unset($question_list_temp);
        }

        return $question_list;
    }

}